package algorithm;

import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedList;

public class leetcode_0435 {
    public static void main(String[] args) {
        int[][] list={{1,2},{2,3},{3,4},{1,3}};
        eraseOverlapIntervals(list);
    }
    public static int eraseOverlapIntervals(int[][] intervals) {
        Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                if(o1[0]==o2[0]){
                    return o1[1]-o2[1];
                }
                else{
                    return o1[0]-o2[0];
                }
            }
        });
        int num=0;
        int tem=intervals[0][0];
        LinkedList<int[]> list=new LinkedList<>();
        int len=intervals.length;
        list.add(intervals[0]);
        for(int i=1;i<len;++i){
            if(intervals[i][0]==tem){
                num++;
            }
            else{
                list.add(intervals[i]);
                tem=intervals[i][0];
            }
        }
        len=list.size();
        for(int i=0;i+1<len;++i){
            if(list.get(i)[1]<=list.get(i+1)[0]){

            }
            else if(list.get(i)[1]<=list.get(i+1)[1]){
                num++;
                list.remove(i+1);
                i--;
                len--;
            }
            else{
                num++;
                list.remove(i);
                i--;
                len--;
            }
        }
        return num;
    }
}
